from PyQt6.QtWidgets import (QFrame, QVBoxLayout, QHBoxLayout, QLabel, QPushButton, 
                              QComboBox, QTableWidget, QTableWidgetItem, QHeaderView,
                              QWidget, QCheckBox, QProgressBar, QMessageBox, QSplitter)
from PyQt6.QtCore import Qt, pyqtSignal, QTimer
from PyQt6.QtGui import QColor
from database import db_manager
from websocket_client import websocket_client
from utils.style_manager import StyleManager

class InvitePage(QFrame):
    consent_finished = pyqtSignal()
    
    def __init__(self, parent=None):
        super().__init__(parent)
        self.auto_consent_status = {}  # 存储每个账号的自动同意状态，默认关闭
        self.setup_ui()
        
        # 连接WebSocket信号
        websocket_client.consent_finished.connect(self.refresh_task_table)
        self.consent_finished.connect(self.refresh_task_table)
        
        # 启动任务表格自动刷新定时器
        self.start_task_table_refresh_timer()
        
        # 同步自动同意状态
        self.sync_auto_consent_status()
    
    def closeEvent(self, event):
        """关闭事件处理"""
        self.stop_queue_monitor()
        self.stop_task_table_refresh_timer()
        super().closeEvent(event)
    
    def start_task_table_refresh_timer(self):
        """启动任务表格自动刷新定时器"""
        try:
            # 创建定时器来定期刷新任务表格数据
            self.task_table_refresh_timer = QTimer()
            self.task_table_refresh_timer.timeout.connect(self.auto_refresh_task_table)
            self.task_table_refresh_timer.start(5000)  # 每5秒自动刷新一次
            
            print("✅ 任务表格自动刷新定时器已启动")
        except Exception as e:
            print(f"❌ 启动任务表格自动刷新定时器失败: {e}")
    
    def stop_task_table_refresh_timer(self):
        """停止任务表格自动刷新定时器"""
        try:
            if hasattr(self, 'task_table_refresh_timer'):
                self.task_table_refresh_timer.stop()
                print("⏹️ 任务表格自动刷新定时器已停止")
        except Exception as e:
            print(f"❌ 停止任务表格自动刷新定时器失败: {e}")
    
    def auto_refresh_task_table(self):
        """自动刷新任务表格数据"""
        try:
            # 只在当前显示任务表格时才刷新
            if hasattr(self, 'current_table') and self.current_table == "task":
                # 更新执行状态标签
                self.update_execution_status()
                # 更新队列状态
                self.update_queue_status()
                # 刷新表格数据（但不重新创建整个表格，只更新数据）
                self.refresh_task_table_data_only()
                # 减少日志输出，避免刷屏
                # print("🔄 任务表格数据已自动刷新")
        except Exception as e:
            print(f"❌ 自动刷新任务表格失败: {e}")
    
    def refresh_task_table_data_only(self):
        """只刷新任务表格数据，不重新创建表格结构"""
        try:
            # 从数据库获取最新的账号数据
            accounts = db_manager.get_all_accounts()
            consent_stats = db_manager.get_account_consent_stats()
            
            # 更新表格行数
            self.task_table.setRowCount(len(accounts))
            
            for row, account in enumerate(accounts):
                user_name = account.get('user_name', '')
                
                # 更新复选框
                if not self.task_table.cellWidget(row, 0):
                    checkbox = QCheckBox()
                    checkbox.setChecked(True)
                    checkbox.setEnabled(False)
                    self.task_table.setCellWidget(row, 0, checkbox)
                
                # 更新No列
                self.task_table.setItem(row, 1, QTableWidgetItem(str(row + 1)))
                
                # 更新账号列
                display_name = account.get('nick_name') or account.get('user_name', '')
                self.task_table.setItem(row, 2, QTableWidgetItem(display_name))
                
                # 更新执行列
                stats = consent_stats.get(user_name, {})
                consent_operations = stats.get('consent_operations', 0)
                total_invites = stats.get('total_invites', 0)
                execution = f"{consent_operations}/{total_invites}"
                self.task_table.setItem(row, 3, QTableWidgetItem(execution))
                
                # 更新进度列
                if total_invites > 0:
                    progress_percentage = round((consent_operations / total_invites) * 100)
                    progress = f"{progress_percentage}%"
                else:
                    progress = "0%"
                self.task_table.setItem(row, 4, QTableWidgetItem(progress))
                
                # 更新明细列
                successful_consents = stats.get('successful_consents', 0)
                failed_consents = stats.get('failed_consents', 0)
                details = f"成功{successful_consents}/失败{failed_consents}"
                self.task_table.setItem(row, 5, QTableWidgetItem(details))
                
                # 更新重复率列
                duplication_rate = account.get('duplication_rate', '0/0 0%')
                self.task_table.setItem(row, 6, QTableWidgetItem(duplication_rate))
                
                # 更新状态列
                self.update_status_column(row, user_name)
                
                # 更新操作列按钮
                self.update_operation_buttons(row, user_name)
                
        except Exception as e:
            print(f"❌ 刷新任务表格数据失败: {e}")
    
    def update_execution_status(self):
        """更新执行状态标签"""
        try:
            accounts = db_manager.get_all_accounts()
            online_accounts = [acc for acc in accounts if acc.get('status', 0) > 0]
            enabled_accounts = [acc for acc in accounts if self.auto_consent_status.get(acc.get('user_name', ''), False)]
            
            total_online = len(online_accounts)
            total_enabled = len(enabled_accounts)
            
            # 更新状态标签
            if hasattr(self, 'status_label'):
                self.status_label.setText(f"执行账号数: {total_enabled}/{total_online}")
                
                # 根据状态调整颜色
                if total_enabled == 0:
                    StyleManager.set_label_style(self.status_label, "status-danger")
                elif total_enabled < total_online:
                    StyleManager.set_label_style(self.status_label, "status-warning")
                else:
                    StyleManager.set_label_style(self.status_label, "status-success")
                    
        except Exception as e:
            print(f"❌ 更新执行状态失败: {e}")
    
    def update_operation_buttons(self, row, user_name):
        """更新操作列按钮"""
        try:
            # 检查是否已有操作按钮
            operation_widget = self.task_table.cellWidget(row, 8)
            if not operation_widget:
                # 如果没有操作按钮，创建新的
                operation_widget = QWidget()
                operation_layout = QHBoxLayout(operation_widget)
                operation_layout.setContentsMargins(4, 4, 4, 4)
                operation_layout.setSpacing(4)
                
                # 创建开关按钮
                switch_btn = QPushButton("关闭" if self.auto_consent_status.get(user_name, False) else "开启")
                switch_btn.setFixedSize(70, 30)
                switch_btn.clicked.connect(lambda checked, r=row, u=user_name, b=switch_btn: self.toggle_auto_consent(r, u, b))
                
                # 设置按钮样式
                if self.auto_consent_status.get(user_name, False):
                    # 开启状态：显示"关闭"，红色
                    switch_btn.setStyleSheet("""
                        QPushButton {
                            background-color: #dc3545;
                            color: white;
                            border: none;
                            border-radius: 2px;
                            font-size: 13px;
                        }
                        QPushButton:hover {
                            background-color: #c82333;
                        }
                    """)
                    switch_btn.setToolTip("自动同意进群已开启，点击可关闭")
                else:
                    # 关闭状态：显示"开启"，绿色
                    switch_btn.setStyleSheet("""
                        QPushButton {
                            background-color: #28a745;
                            color: white;
                            border: none;
                            border-radius: 2px;
                            font-size: 13px;
                        }
                        QPushButton:hover {
                            background-color: #218838;
                        }
                    """)
                    switch_btn.setToolTip("自动同意进群已关闭，点击可开启")
                
                operation_layout.addWidget(switch_btn)
                
                # 添加其他按钮
                button_configs = [
                    ("清空", "#007bff"),
                    ("更多", "#6c757d")
                ]
                
                for btn_text, bg_color in button_configs:
                    btn = QPushButton(btn_text)
                    btn.setFixedSize(70, 30)
                    btn.setStyleSheet(f"""
                        QPushButton {{
                            background-color: {bg_color};
                            color: white;
                            border: none;
                            border-radius: 3px;
                            font-size: 12px;
                            font-weight: bold;
                            padding: 4px 8px;
                        }}
                        QPushButton:hover {{
                            background-color: {bg_color};
                            opacity: 0.8;
                        }}
                    """)
                    operation_layout.addWidget(btn)
                
                self.task_table.setCellWidget(row, 8, operation_widget)
            else:
                # 如果已有操作按钮，更新开关按钮状态
                for i in range(operation_widget.layout().count()):
                    widget = operation_widget.layout().itemAt(i).widget()
                    if isinstance(widget, QPushButton) and widget.text() in ["开启", "关闭"]:
                        current_status = self.auto_consent_status.get(user_name, False)
                        widget.setText("关闭" if current_status else "开启")
                        
                        # 更新按钮样式
                        if current_status:
                            # 自动同意已开启：按钮显示"关闭"，用红色样式
                            widget.setStyleSheet("""
                                QPushButton {
                                    background-color: #dc3545;
                                    color: white;
                                    border: none;
                                    border-radius: 2px;
                                    font-size: 13px;
                                }
                                QPushButton:hover {
                                    background-color: #c82333;
                                }
                            """)
                            widget.setToolTip("自动同意进群已开启，点击可关闭")
                        else:
                            # 自动同意已关闭：按钮显示"开启"，用绿色样式
                            widget.setStyleSheet("""
                                QPushButton {
                                    background-color: #28a745;
                                    color: white;
                                    border: none;
                                    border-radius: 2px;
                                    font-size: 13px;
                                }
                                QPushButton:hover {
                                    background-color: #218838;
                                }
                            """)
                            widget.setToolTip("自动同意进群已关闭，点击可开启")
                        break
                        
        except Exception as e:
            print(f"❌ 更新操作按钮失败: {e}")
    
    def sync_auto_consent_status(self):
        """同步自动同意状态"""
        try:
            # 从WebSocket客户端获取当前状态
            if hasattr(websocket_client, 'auto_consent_status'):
                self.auto_consent_status = websocket_client.auto_consent_status.copy()
                print(f"✅ 已同步WebSocket客户端的自动同意状态: {len(self.auto_consent_status)} 个账号")
            else:
                print("ℹ️ WebSocket客户端没有自动同意状态信息")
        except Exception as e:
            print(f"❌ 同步自动同意状态失败: {e}")
    
    def setup_ui(self):
        """设置UI"""
        layout = QVBoxLayout(self)
        layout.setSpacing(10)
        
        # 控制区域
        self.control_frame = QFrame()
        control_layout = QHBoxLayout(self.control_frame)
        control_layout.setSpacing(15)
        
        # 接口选择
        interface_label = QLabel("接口:")
        StyleManager.set_label_style(interface_label, "subtitle")
        control_layout.addWidget(interface_label)
        
        self.interface_combo = QComboBox()
        # 支持0-60秒的延时范围
        self.interface_combo.addItems([
            "0秒", "1秒", "2秒", "3秒", "5秒", "10秒", "15秒", "20秒", "30秒", "45秒", "60秒"
        ])
        self.interface_combo.currentTextChanged.connect(self.on_interval_changed)
        self.interface_combo.setCurrentText("60秒")  # 设置默认值
        control_layout.addWidget(self.interface_combo)
        
        # 执行状态
        self.status_label = QLabel("执行账号数: 0/3")
        StyleManager.set_label_style(self.status_label, "status-danger")
        control_layout.addWidget(self.status_label)
        
        # 队列状态显示
        self.queue_status_label = QLabel("队列: 0 | 间隔: 3秒")
        StyleManager.set_label_style(self.queue_status_label, "status-info")
        control_layout.addWidget(self.queue_status_label)
        
        control_layout.addStretch()
        
        # 全部开始按钮
        self.start_btn = QPushButton("全部开始")
        self.start_btn.clicked.connect(self.on_group_invite)
        # 添加显示任务表格的功能
        self.start_btn.clicked.connect(lambda: self.show_task_table())
        StyleManager.set_button_style(self.start_btn, "success")
        control_layout.addWidget(self.start_btn)
        
        # 任务按钮
        self.task_btn = QPushButton("任务管理")
        self.task_btn.clicked.connect(self.show_task_table)
        StyleManager.set_button_style(self.task_btn, "info")
        
        # 邀请明细按钮
        self.detail_btn = QPushButton("邀请明细")
        self.detail_btn.clicked.connect(self.show_detail_table)
        StyleManager.set_button_style(self.detail_btn, "info")
        
        # 将切换按钮从控制区域中分离出来，创建独立的按钮区域
        self.button_frame = QFrame()
        button_layout = QHBoxLayout(self.button_frame)
        button_layout.setSpacing(10)
        
        # 将按钮移动到独立的按钮区域
        button_layout.addWidget(self.task_btn)
        button_layout.addWidget(self.detail_btn)
        button_layout.addStretch()
        
        layout.addWidget(self.button_frame)
        layout.addWidget(self.control_frame)
        
        # 创建两个表格区域
        self.create_task_table()
        self.create_detail_table()
        
        # 默认显示任务表格
        self.current_table = "task"
        self.show_table("task")
        
        # 设置表格数据
        self.setup_task_table_data()
        self.setup_detail_table_data()
        
        # 设置默认按钮样式，任务管理按钮为选中状态
        self.update_button_styles("task")
        
        # 初始化执行状态和队列状态
        self.update_execution_status()
        self.update_queue_status()
        
        layout.addWidget(self.table_container)

        # 明细底部按钮区域（默认隐藏，仅在邀请明细页显示）
        self.detail_footer_frame = QFrame()
        detail_footer_layout = QHBoxLayout(self.detail_footer_frame)
        detail_footer_layout.setSpacing(10)
        detail_footer_layout.addStretch()
        self.clear_detail_bottom_btn = QPushButton("清空明细")
        self.clear_detail_bottom_btn.clicked.connect(self.on_clear_detail_clicked)
        StyleManager.set_button_style(self.clear_detail_bottom_btn, "danger")
        detail_footer_layout.addWidget(self.clear_detail_bottom_btn)
        self.detail_footer_frame.setVisible(False)
        layout.addWidget(self.detail_footer_frame)
    
    def create_task_table(self):
        """创建任务表格（显示账号执行状态）"""
        self.task_table = QTableWidget()
        self.task_table.setColumnCount(9)
        self.task_table.setHorizontalHeaderLabels([
            "", "No", "账号", "执行", "进度", "明细", "重复率", "状态", "操作"
        ])
        
        # 设置表格撑满容器
        self.task_table.horizontalHeader().setStretchLastSection(True)
        self.task_table.horizontalHeader().setSectionResizeMode(QHeaderView.ResizeMode.ResizeToContents)
        
        # 隐藏垂直表头
        self.task_table.verticalHeader().setVisible(False)
        
        # 设置表格为不可编辑（只读模式）
        self.task_table.setEditTriggers(QTableWidget.EditTrigger.NoEditTriggers)
        # 支持选中整行
        self.task_table.setSelectionBehavior(QTableWidget.SelectionBehavior.SelectRows)
        self.task_table.setSelectionMode(QTableWidget.SelectionMode.SingleSelection)
        
        # 设置表格样式
        self.task_table.setAlternatingRowColors(True)
        # 设置行高以适应按钮
        self.task_table.verticalHeader().setDefaultSectionSize(40)
        self.task_table.verticalHeader().setMinimumSectionSize(35)
        self.task_table.setStyleSheet("""
            QTableWidget {
                gridline-color: #d0d0d0;
                background-color: white;
                alternate-background-color: #f8f9fa;
                selection-background-color: #007bff;
                selection-color: white;
            }
            QTableWidget::item {
                padding: 4px;
                border: none;
            }
            QHeaderView::section {
                background-color: #f8f9fa;
                padding: 8px;
                border: 1px solid #d0d0d0;
                font-weight: bold;
            }
        """)
    
    def create_detail_table(self):
        """创建邀请明细表格"""
        self.detail_table = QTableWidget()
        self.detail_table.setColumnCount(7)
        self.detail_table.setHorizontalHeaderLabels([
            "邀请时间", "账号", "群名称", "邀请人", "邀请结果", "进群时间", "备注"
        ])
        
        # 设置表格撑满容器
        self.detail_table.horizontalHeader().setStretchLastSection(True)
        self.detail_table.horizontalHeader().setSectionResizeMode(QHeaderView.ResizeMode.ResizeToContents)
        
        # 隐藏垂直表头
        self.detail_table.verticalHeader().setVisible(False)
        
        # 设置表格样式
        self.detail_table.setAlternatingRowColors(True)
        # 支持选中整行
        self.detail_table.setSelectionBehavior(QTableWidget.SelectionBehavior.SelectRows)
        self.detail_table.setSelectionMode(QTableWidget.SelectionMode.SingleSelection)
        # 设置行高以适应按钮
        self.detail_table.verticalHeader().setDefaultSectionSize(35)
        self.detail_table.verticalHeader().setMinimumSectionSize(30)
        self.detail_table.setStyleSheet("""
            QTableWidget {
                gridline-color: #d0d0d0;
                background-color: white;
                alternate-background-color: #f8f9fa;
                selection-background-color: #007bff;
                selection-color: white;
            }
            QTableWidget::item {
                padding: 4px;
                border: none;
            }
            QHeaderView::section {
                background-color: #f8f9fa;
                padding: 8px;
                border: 1px solid #d0d0d0;
                font-weight: bold;
            }
        """)

    def on_clear_detail_clicked(self):
        """清空邀请明细表格"""
        try:
            from PyQt6.QtWidgets import QMessageBox
            reply = QMessageBox.question(
                self,
                "确认清空",
                "确定要清空全部邀请明细吗？此操作不可恢复。",
                QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No,
                QMessageBox.StandardButton.No,
            )
            if reply != QMessageBox.StandardButton.Yes:
                return

            # 清空数据库邀请明细
            from database import db_manager
            ok = db_manager.clear_all_invite_details()
            if not ok:
                QMessageBox.critical(self, "错误", "清空数据库邀请明细失败")
                return

            # 清空表格显示并提示
            self.detail_table.setRowCount(0)
            QMessageBox.information(self, "完成", "邀请明细已清空")
        except Exception as e:
            from PyQt6.QtWidgets import QMessageBox
            QMessageBox.critical(self, "错误", f"清空明细失败: {e}")
    

    
    def setup_task_table_data(self):
        """设置主表格数据"""
        # 从数据库获取账号数据
        accounts = db_manager.get_all_accounts()
        # 获取同意进群操作统计（不论成功与失败）
        consent_stats = db_manager.get_account_consent_stats()
        
        self.task_table.setRowCount(len(accounts))
        for row, account in enumerate(accounts):
            # 复选框
            checkbox = QCheckBox()
            checkbox.setChecked(True)  # 默认选中
            checkbox.setEnabled(False)  # 设置为不可编辑
            self.task_table.setCellWidget(row, 0, checkbox)
            # No列
            self.task_table.setItem(row, 1, QTableWidgetItem(str(row + 1)))
            # 账号列 - 显示昵称，如果没有则显示用户名
            display_name = account.get('nick_name') or account.get('user_name', '')
            self.task_table.setItem(row, 2, QTableWidgetItem(display_name))
            # 执行列：同意进群操作次数（不论成功与失败）/邀请进群数
            user_name = account.get('user_name', '')
            stats = consent_stats.get(user_name, {})
            consent_operations = stats.get('consent_operations', 0)
            total_invites = stats.get('total_invites', 0)
            execution = f"{consent_operations}/{total_invites}"
            self.task_table.setItem(row, 3, QTableWidgetItem(execution))
            
            # 进度列：基于执行列计算进度百分比
            if total_invites > 0:
                progress_percentage = round((consent_operations / total_invites) * 100)
                progress = f"{progress_percentage}%"
            else:
                progress = "0%"
            self.task_table.setItem(row, 4, QTableWidgetItem(progress))
            
            # 明细列：同意进群成功数/同意进群失败数
            successful_consents = stats.get('successful_consents', 0)
            failed_consents = stats.get('failed_consents', 0)
            details = f"成功{successful_consents}/失败{failed_consents}"
            self.task_table.setItem(row, 5, QTableWidgetItem(details))
            
            # 重复率列
            duplication_rate = account.get('duplication_rate', '0/0 0%')
            self.task_table.setItem(row, 6, QTableWidgetItem(duplication_rate))
            
            # 状态列：显示在线状态 + 自动同意状态
            online_status = account.get('status', 0)
            is_online = online_status > 0
            auto_consent_enabled = self.auto_consent_status.get(user_name, False)  # 默认关闭
            
            # 构建状态文本
            if is_online:
                if auto_consent_enabled:
                    status_text = "在线-开启"
                    status_color = Qt.GlobalColor.green
                else:
                    status_text = "在线-关闭"
                    status_color = QColor("#FFA500")  # 橙色
            else:
                if auto_consent_enabled:
                    status_text = "离线-开启"
                    status_color = Qt.GlobalColor.gray
                else:
                    status_text = "离线-关闭"
                    status_color = Qt.GlobalColor.red
            
            status_item = QTableWidgetItem(status_text)
            status_item.setForeground(status_color)
            self.task_table.setItem(row, 7, status_item)
            
            # 操作列 - 添加按钮
            operation_widget = QWidget()
            operation_layout = QHBoxLayout(operation_widget)
            operation_layout.setContentsMargins(4, 4, 4, 4)  # 增加边距
            operation_layout.setSpacing(4)  # 增加按钮间距
            
            # 添加操作按钮 - 按照图片中的样式
            button_configs = [
                ("开关", "#000000"),  # 黑色按钮
                ("清空", "#007bff"),  # 蓝色按钮
                ("更多", "#6c757d")   # 灰色按钮
            ]
            
            for btn_text, bg_color in button_configs:
                btn = QPushButton(btn_text)
                btn.setFixedSize(70, 30)  # 增加按钮尺寸，确保文字和按钮完整显示
                btn.setStyleSheet(f"""
                    QPushButton {{
                        background-color: {bg_color};
                        color: white;
                        border: none;
                        border-radius: 3px;
                        font-size: 12px;
                        font-weight: bold;
                        padding: 4px 8px;
                    }}
                    QPushButton:hover {{
                        background-color: {bg_color};
                        opacity: 0.8;
                    }}
                """)
                if btn_text == "开关":
                    # 设置初始文本和颜色
                    status = self.auto_consent_status.get(user_name, False)  # 默认关闭
                    btn.setText("关闭" if status else "开启")
                    
                    # 检查账号是否在线，只有在线账号才能操作开关
                    online_status = account.get('status', 0)
                    is_online = online_status > 0
                    btn.setEnabled(is_online)
                    
                    # 根据状态和在线情况设置颜色
                    if not is_online:
                        # 离线状态：灰色，不可操作
                        btn.setStyleSheet("""
                            QPushButton {
                                background-color: #6c757d;
                                color: #adb5bd;
                                border: none;
                                border-radius: 3px;
                                font-size: 12px;
                                font-weight: bold;
                                padding: 4px 8px;
                            }
                        """)
                        btn.setToolTip("账号离线，无法操作开关")
                    elif status:
                        # 在线且开启：按钮显示"关闭"，用红色样式
                        btn.setStyleSheet("""
                            QPushButton {
                                background-color: #dc3545;
                                color: white;
                                border: none;
                                border-radius: 3px;
                                font-size: 12px;
                                font-weight: bold;
                                padding: 4px 8px;
                            }
                            QPushButton:hover {
                                background-color: #c82333;
                            }
                        """)
                        btn.setToolTip("自动同意进群已开启，点击可关闭")
                    else:
                        # 在线但关闭：按钮显示"开启"，用绿色样式
                        btn.setStyleSheet("""
                            QPushButton {
                                background-color: #28a745;
                                color: white;
                                border: none;
                                border-radius: 3px;
                                font-size: 12px;
                                font-weight: bold;
                                padding: 4px 8px;
                            }
                            QPushButton:hover {
                                background-color: #218838;
                            }
                        """)
                        btn.setToolTip("自动同意进群已关闭，点击可开启")
                    
                    btn.clicked.connect(lambda checked, row=row, user_name=user_name, btn=btn: self.toggle_auto_consent(row, user_name, btn))
                elif btn_text == "清空":
                    btn.clicked.connect(lambda checked, row=row, user_name=user_name: self.clear_account_data(row, user_name))
                    btn.setToolTip("清空统计数量")
                elif btn_text == "更多":
                    btn.clicked.connect(lambda checked, row=row, user_name=user_name: self.show_more_options(row, user_name))
                    btn.setToolTip("更多操作选项")
                
                operation_layout.addWidget(btn)
            
            operation_layout.addStretch()
            self.task_table.setCellWidget(row, 8, operation_widget)
        self.task_table.resizeRowsToContents()
    
    def setup_detail_table_data(self):
        """设置邀请明细表格数据"""
        # 从数据库获取邀请明细数据
        details = db_manager.get_invite_details()
        
        # 如果没有数据，显示空表格
        if not details:
            self.detail_table.setRowCount(0)
            return
        
        self.detail_table.setRowCount(len(details))
        
        for row, detail in enumerate(details):
            # 时间
            invite_time = detail.get('invite_time', '')
            if invite_time:
                # 格式化时间显示
                try:
                    from datetime import datetime
                    dt = datetime.fromisoformat(invite_time.replace('Z', '+00:00'))
                    formatted_time = dt.strftime('%Y-%m-%d %H:%M:%S')
                except:
                    formatted_time = invite_time
            else:
                formatted_time = ''
            self.detail_table.setItem(row, 0, QTableWidgetItem(formatted_time))
            
            # 账号
            self.detail_table.setItem(row, 1, QTableWidgetItem(detail.get('user_name', '')))
            
            # 群名称
            self.detail_table.setItem(row, 2, QTableWidgetItem(detail.get('group_name', '')))
            
            # 邀请人
            inviter_name = detail.get('inviter_name', '')
            self.detail_table.setItem(row, 3, QTableWidgetItem(inviter_name))
            
            # 邀请结果
            result = detail.get('invite_result', '')
            result_item = QTableWidgetItem(result)
            if result == '已同意':
                result_item.setForeground(Qt.GlobalColor.green)
            elif result == '失败':
                result_item.setForeground(Qt.GlobalColor.red)
            elif result == '等待中':
                result_item.setForeground(Qt.GlobalColor.blue)
            self.detail_table.setItem(row, 4, result_item)
            
            # 进群时间
            join_time = detail.get('join_time', '')
            if join_time:
                # 格式化时间显示
                try:
                    from datetime import datetime
                    dt = datetime.fromisoformat(join_time.replace('Z', '+00:00'))
                    formatted_join_time = dt.strftime('%Y-%m-%d %H:%M:%S')
                except:
                    formatted_join_time = join_time
            else:
                formatted_join_time = '未进群'
            self.detail_table.setItem(row, 5, QTableWidgetItem(formatted_join_time))
            
            # 备注
            self.detail_table.setItem(row, 6, QTableWidgetItem(detail.get('remark', '')))
    
    def show_table(self, table_name):
        """显示指定的表格"""
        # 清除当前表格容器
        if hasattr(self, 'table_container'):
            while self.table_container.layout().count():
                child = self.table_container.layout().takeAt(0)
                if child.widget():
                    child.widget().setParent(None)
        else:
            # 创建表格容器
            self.table_container = QWidget()
            self.table_container.setLayout(QVBoxLayout())
        
        # 显示新表格
        if table_name == "task":
            self.table_container.layout().addWidget(self.task_table)
            # 显示控制区域（间隔设置、状态显示等）
            self.show_control_elements(True)
            if hasattr(self, 'detail_footer_frame'):
                self.detail_footer_frame.setVisible(False)
        elif table_name == "detail":
            self.table_container.layout().addWidget(self.detail_table)
            # 隐藏控制区域，只显示纯净的邀请明细
            self.show_control_elements(False)
            if hasattr(self, 'detail_footer_frame'):
                self.detail_footer_frame.setVisible(True)
        
        self.current_table = table_name

    def show_control_elements(self, show: bool):
        """显示或隐藏控制元素"""
        if hasattr(self, 'control_frame'):
            self.control_frame.setVisible(show)
        
        # 按钮区域始终可见
        if hasattr(self, 'button_frame'):
            self.button_frame.setVisible(True)
        
        # 根据当前显示状态刷新数据
        if show:
            # 显示任务管理时，更新任务数据
            self.setup_task_table_data()
        else:
            # 显示邀请明细时，更新明细数据
            self.setup_detail_table_data()
    
    def show_task_table(self):
        """显示任务表格"""
        self.show_table("task")
        self.update_button_styles("task")
        
        # 立即刷新任务表格数据
        self.refresh_task_table_data_only()
        self.update_execution_status()
        self.update_queue_status()
    

    
    def show_detail_table(self):
        """显示邀请明细表格"""
        self.show_table("detail")
        self.update_button_styles("detail")
    
    def update_button_styles(self, active_table):
        """更新按钮样式"""
        # 重置所有按钮样式
        self.task_btn.setStyleSheet("""
            QPushButton {
                background-color: transparent;
                color: #007bff;
                border: none;
                font-weight: bold;
                font-size: 14px;
                padding: 8px 16px;
            }
            QPushButton:hover {
                color: #0056b3;
                text-decoration: underline;
            }
        """)
        
        self.detail_btn.setStyleSheet("""
            QPushButton {
                background-color: transparent;
                color: #007bff;
                border: none;
                font-weight: bold;
                font-size: 14px;
                padding: 8px 16px;
            }
            QPushButton:hover {
                color: #0056b3;
                text-decoration: underline;
            }
        """)
        
        # 突出显示当前选中的按钮
        if active_table == "task":
            self.task_btn.setStyleSheet("""
                QPushButton {
                    background-color: #007bff;
                    color: white;
                    border: none;
                    font-weight: bold;
                    font-size: 14px;
                    padding: 8px 16px;
                    border-radius: 4px;
                }
                QPushButton:hover {
                    background-color: #0056b3;
                }
            """)
        elif active_table == "detail":
            self.detail_btn.setStyleSheet("""
                QPushButton {
                    background-color: #007bff;
                    color: white;
                    border: none;
                    font-weight: bold;
                    font-size: 14px;
                    padding: 8px 16px;
                    border-radius: 4px;
                }
                QPushButton:hover {
                    background-color: #0056b3;
                }
            """)
                

    
    def on_group_invite(self):
        """全部开始按钮点击事件"""
        try:
            # 开启所有处于关闭状态的在线账号开关
            accounts = db_manager.get_all_accounts()
            enabled_count = 0
            
            for account in accounts:
                user_name = account.get('user_name', '')
                if user_name:
                    # 只对在线且当前状态为关闭的账号开启
                    online_status = account.get('status', 0)
                    is_online = online_status > 0
                    current_status = self.auto_consent_status.get(user_name, False)  # 默认关闭
                    
                    if is_online and not current_status:
                        # 设置自动同意状态为开启
                        self.auto_consent_status[user_name] = True
                        enabled_count += 1
            
            # 刷新表格显示以更新开关按钮状态
            self.setup_task_table_data()
            
            # 如果有账号被开启，启动WebSocket定时器
            if enabled_count > 0:
                try:
                    from websocket_client import websocket_client
                    if hasattr(websocket_client, 'start_consent_timer'):
                        websocket_client.start_consent_timer()
                        print(f"✅ WebSocket定时器已启动 - 批量开启 {enabled_count} 个账号")
                    else:
                        print(f"⚠️ WebSocket客户端没有start_consent_timer方法")
                except Exception as e:
                    print(f"启动WebSocket定时器失败: {e}")
            
            # 立即更新执行状态和队列状态
            self.update_execution_status()
            self.update_queue_status()
            
            # 显示操作结果
            if enabled_count > 0:
                from PyQt6.QtWidgets import QMessageBox
                QMessageBox.information(self, "成功", f"已开启 {enabled_count} 个账号的自动同意开关")
            else:
                from PyQt6.QtWidgets import QMessageBox
                QMessageBox.information(self, "提示", "没有需要开启的账号开关（所有在线账号已开启或无在线账号）")
                
        except Exception as e:
            from PyQt6.QtWidgets import QMessageBox
            QMessageBox.critical(self, "错误", f"操作出错: {str(e)}")
    
    def on_invite_task(self):
        """任务按钮点击事件（已废弃，使用show_task_table替代）"""
        pass
    
    def on_invite_detail(self):
        """邀请明细按钮点击事件（已废弃，使用show_detail_table替代）"""
        pass 
    
    def on_interval_changed(self, text: str):
        """处理间隔设置变化"""
        try:
            # 从文本中提取秒数
            if text.endswith('秒'):
                seconds = int(text[:-1])  # 去掉"秒"字
            else:
                seconds = int(text)
            
            # 验证延时范围
            if seconds < 0 or seconds > 60:
                print(f"⚠️ 延时设置超出范围 (0-60秒): {seconds}秒")
                return
            
            # 设置WebSocket客户端的间隔时间
            try:
                from websocket_client import websocket_client
                if hasattr(websocket_client, 'set_interval_seconds'):
                    success = websocket_client.set_interval_seconds(seconds)
                    if success:
                        print(f"✅ WebSocket客户端间隔时间已更新为: {seconds}秒")
                    else:
                        print(f"❌ WebSocket客户端间隔时间更新失败")
                else:
                    print(f"⚠️ WebSocket客户端没有set_interval_seconds方法")
            except Exception as e:
                print(f"❌ 更新WebSocket客户端间隔时间失败: {e}")
            
            # 更新队列状态显示
            self.update_queue_status()
            
            if seconds == 0:
                print(f"✅ 延时设置已更新为: {text} (立即处理)")
            else:
                print(f"✅ 延时设置已更新为: {text}")
            
        except Exception as e:
            print(f"更新延时设置时出错: {e}")
    
    def update_queue_status(self):
        if not hasattr(self, 'queue_status_label'):
            return
        """更新队列状态显示"""
        try:
            # 获取当前选择的间隔模式
            current_interval = self.interface_combo.currentText()
            
            # 从WebSocket客户端获取真实队列大小
            queue_size = 0
            try:
                if hasattr(websocket_client, 'get_consent_queue_size'):
                    queue_size = websocket_client.get_consent_queue_size()
                else:
                    print("⚠️ WebSocket客户端没有get_consent_queue_size方法")
            except Exception as e:
                print(f"❌ 获取队列大小失败: {e}")
            
            # 显示当前使用的间隔设置
            if current_interval == "0秒":
                interval_display = "0秒 (立即处理)"
            elif current_interval != "1秒":  # 如果标准接口不是默认的1秒
                interval_display = f"{current_interval}"
            else:
                interval_display = "默认"
            
            self.queue_status_label.setText(f"队列: {queue_size} | 间隔: {interval_display}")
            
            # 根据队列大小调整颜色
            if queue_size == 0:  # 队列为空
                StyleManager.set_label_style(self.queue_status_label, "status-muted")
            elif queue_size < 5:  # 队列较小
                StyleManager.set_label_style(self.queue_status_label, "status-info")
            elif queue_size < 10:  # 队列中等
                StyleManager.set_label_style(self.queue_status_label, "status-warning")
            else:  # 队列较大
                StyleManager.set_label_style(self.queue_status_label, "status-danger")
                
        except Exception as e:
            print(f"更新队列状态时出错: {e}")
            # 设置默认状态
            try:
                self.queue_status_label.setText("队列: 状态异常")
                StyleManager.set_label_style(self.queue_status_label, "status-danger")
            except:
                pass
    
    def start_queue_monitor(self):
        """启动队列监控定时器"""
        from PyQt6.QtCore import QTimer
        
        # 创建定时器来定期更新队列状态
        self.queue_timer = QTimer()
        self.queue_timer.timeout.connect(self.update_queue_status)
        self.queue_timer.start(3000)  # 每3秒更新一次，减少系统负担
        
        # 启动同意进群定时器
        # http_client.start_consent_timer() # This line was removed as per the new_code, as the consent timer is now managed by the interface.
        
        print("队列监控已启动")
    
    def stop_queue_monitor(self):
        """停止队列监控"""
        if hasattr(self, 'queue_timer'):
            self.queue_timer.stop()
        
        # http_client.stop_consent_timer() # This line was removed as per the new_code, as the consent timer is now managed by the interface.
        print("队列监控已停止") 

    def refresh_task_table(self):
        """主线程安全刷新任务表格"""
        self.setup_task_table_data() 

    def toggle_auto_consent(self, row, user_name, btn):
        """切换账号的自动同意进群状态"""
        current = self.auto_consent_status.get(user_name, False)  # 默认关闭
        new_status = not current
        self.auto_consent_status[user_name] = new_status
        btn.setText("关闭" if new_status else "开启")
        
                # 更新按钮颜色和提示文本
        if new_status:
            # 开启状态：显示"关闭"，红色
            btn.setStyleSheet("""
                QPushButton {
                    background-color: #dc3545;
                    color: white;
                    border: none;
                    border-radius: 2px;
                    font-size: 13px;
                }
                QPushButton:hover {
                    background-color: #c82333;
                }
            """)
            btn.setToolTip("自动同意进群已开启，点击可关闭")
        else:
            # 关闭状态：显示"开启"，绿色
            btn.setStyleSheet("""
                QPushButton {
                    background-color: #28a745;
                    color: white;
                    border: none;
                    border-radius: 2px;
                    font-size: 13px;
                }
                QPushButton:hover {
                    background-color: #218838;
                }
            """)
            btn.setToolTip("自动同意进群已关闭，点击可开启")
        
        # 更新状态列显示
        self.update_status_column(row, user_name)
        
        # 通知WebSocket客户端更新自动同意状态
        try:
            from websocket_client import websocket_client
            # 设置该用户的自动同意状态
            if hasattr(websocket_client, 'set_auto_consent_status'):
                websocket_client.set_auto_consent_status(user_name, new_status)
                
                # 根据状态启动或停止定时器
                if new_status:
                    # 开启状态：启动定时器
                    if hasattr(websocket_client, 'start_consent_timer'):
                        websocket_client.start_consent_timer()
                        print(f"✅ WebSocket定时器已启动 - {user_name}")
                    else:
                        print(f"⚠️ WebSocket客户端没有start_consent_timer方法")
                else:
                    # 关闭状态：检查是否还有其他账号开启，如果没有则停止定时器
                    if hasattr(websocket_client, 'stop_consent_timer'):
                        # 检查是否还有其他账号开启
                        other_enabled = any(status for name, status in self.auto_consent_status.items() 
                                          if name != user_name and status)
                        if not other_enabled:
                            websocket_client.stop_consent_timer()
                            print(f"✅ WebSocket定时器已停止 - 所有账号都已关闭")
                        else:
                            print(f"ℹ️ WebSocket定时器继续运行 - 还有其他账号开启")
                    else:
                        print(f"⚠️ WebSocket客户端没有stop_consent_timer方法")
                        
            print(f"账号 {user_name} 自动同意进群状态已{'开启' if new_status else '关闭'}")
        except Exception as e:
            print(f"更新自动同意状态失败: {user_name}, 错误: {e}")
        
        # 立即更新执行状态和队列状态
        self.update_execution_status()
        self.update_queue_status()
        
        # 保存状态到数据库（可选）
        try:
            from database import db_manager
            # 这里可以扩展数据库表来保存自动同意状态
            # db_manager.update_auto_consent_status(user_name, new_status)
        except Exception as e:
            print(f"保存自动同意状态到数据库失败: {user_name}, 错误: {e}")
    
    def update_status_column(self, row, user_name):
        """更新指定行的状态列显示"""
        try:
            # 获取账号信息
            accounts = db_manager.get_all_accounts()
            if row < len(accounts):
                account = accounts[row]
                online_status = account.get('status', 0)
                is_online = online_status > 0
                auto_consent_enabled = self.auto_consent_status.get(user_name, False)  # 默认关闭
                
                # 构建状态文本和颜色
                if is_online:
                    if auto_consent_enabled:
                        status_text = "在线-开启"
                        status_color = Qt.GlobalColor.green
                    else:
                        status_text = "在线-关闭"
                        status_color = QColor("#FFA500")  # 橙色
                else:
                    if auto_consent_enabled:
                        status_text = "离线-开启"
                        status_color = Qt.GlobalColor.gray
                    else:
                        status_text = "离线-关闭"
                        status_color = Qt.GlobalColor.red
                
                # 更新状态列
                status_item = QTableWidgetItem(status_text)
                status_item.setForeground(status_color)
                self.task_table.setItem(row, 7, status_item)
                
        except Exception as e:
            print(f"更新状态列失败: {user_name}, 错误: {e}")

    def clear_account_data(self, row, user_name):
        """清空指定账号的统计数量"""
        try:
            # 直接清空数据，不需要确认对话框
            if db_manager.clear_user_invite_data(user_name):
                # 清空成功，刷新表格显示
                self.setup_task_table_data()
                print(f"✅ 账号 {user_name} 的统计数量已清空")
            else:
                print(f"❌ 清空账号 {user_name} 的数据失败")
                        
        except Exception as e:
            print(f"清空账号数据时出错: {user_name}, 错误: {e}")

    def show_more_options(self, row, user_name):
        """显示更多操作选项"""
        try:
            # 获取账号信息
            accounts = db_manager.get_all_accounts()
            if row < len(accounts):
                account = accounts[row]
                nick_name = account.get('nick_name', '') or user_name
                
                from PyQt6.QtWidgets import QMessageBox
                QMessageBox.information(
                    self,
                    "更多选项",
                    f"账号: {nick_name}\n用户名: {user_name}\n\n"
                    f"更多功能正在开发中...\n\n"
                    f"可能的功能：\n"
                    f"• 导出该账号的邀请记录\n"
                    f"• 设置邀请处理规则\n"
                    f"• 查看详细统计报告\n"
                    f"• 账号设置和配置"
                )
                
        except Exception as e:
            print(f"显示更多选项时出错: {user_name}, 错误: {e}")
    
 